#include"../include/head.h"

int serverLogin(int sockFd)
{
    //1、先接收客户端发来的用户名，然后去数据库里面找
    //   如果在数据库中，把相应的盐值发给客户端
    //   如果不在，通知客户端重新输入
    
    char usrname[20] = {0};
    int sendRet = 0;
    char flag[2] = {0};
    int recvRet = recv(sockFd, usrname, sizeof(usrname), 0);
    ERROR_CHECK(recvRet, -1, "recv");

    char salt[9] = {0};
    char pwd[128] = {0};
    
    int userID = query(usrname, salt, pwd);
    ERROR_CHECK(userID, -1, "query");

    while(userID == 0){
        //非法用户名，通知客户端重新输入
        flag[0] = 'u';
        sendRet = send(sockFd, flag, 1, 0);
        ERROR_CHECK(sendRet, -1, "send");
        //重新接收
        memset(usrname, 0, sizeof(usrname));
        recvRet = recv(sockFd, usrname, sizeof(usrname), 0);
        ERROR_CHECK(recvRet, -1, "recv");
        memset(salt, 0, sizeof(salt));
        memset(pwd, 0, sizeof(pwd));
        userID = query(usrname, salt, pwd);
    }
    //把相应的salt值发送给客户端
    flag[0] = 'a';
    sendRet = send(sockFd, flag, 1, 0);
    sendRet = send(sockFd, salt, sizeof(salt), 0);
    ERROR_CHECK(sendRet, -1, "send salt");

    //2、用户输入了正确的用户名，接收传过来的加密之后的密码
    //   和数据库中保存的进行比对，匹配就返回id，否则返回-1
    char inPwd[128] = {0};
    recvRet = recv(sockFd, inPwd, sizeof(inPwd), 0);
    ERROR_CHECK(recvRet, -1, "recv inPwd");

    /* printf("cryptwd = %s\n", pwd); */
    /* printf("getpwd = %s\n", inPwd); */
    /* printf("%d\n", strcmp(pwd, inPwd)); */

    while(strcmp(pwd, inPwd) != 0)
    {
        //密码输入错误，重新输入
        printf("wrong pwd!\n");
        memset(inPwd, 0, sizeof(inPwd));
        flag[0] = 'p';
        sendRet = send(sockFd, flag, 1, 0);
        ERROR_CHECK(sendRet, -1, "send ret");
        recvRet = recv(sockFd, inPwd, sizeof(inPwd), 0);
        ERROR_CHECK(recvRet, -1, "recv inPwd");
    }

    //用户输入了正确的用户名和密码，返回1
    flag[0] = 'a';
    send(sockFd, flag, 1, 0);
    printf("login successful!\n");
    return userID;
}